package impl

import (
	model "gitee.com/kordar/goadmin/admin/models"
	"gitee.com/kordar/goadmin/reader"
	"github.com/kordar/formatter"
	"github.com/kordar/gocrud"
	gocrudgorm "github.com/kordar/gocrud-gorm"
	"gorm.io/gorm"
)

type DictServiceImpl struct {
	db *gorm.DB
	gocrud.CommonResourceService
}

func NewDictService(db *gorm.DB) *DictServiceImpl {
	return &DictServiceImpl{db: db}
}

func (service DictServiceImpl) ResourceName() string {
	return "dict"
}

func (service DictServiceImpl) Search(body gocrud.SearchBody) gocrud.SearchVO {
	searchBody := gocrudgorm.NewGormSearchBody(body)
	tx := searchBody.GormQuery(service.db, nil).Model(&model.SysDict{})
	queryReader := reader.NewQueryReader(tx, int(body.Page), int(body.PageSize))
	var sysDict []*model.SysDict
	return queryReader.SearchVO(&sysDict, nil)
}

func (service DictServiceImpl) Remove(body gocrud.RemoveBody) error {
	return body.Delete(&model.SysDict{}, service.db, nil)
}

func (service DictServiceImpl) Create(body gocrud.FormBody) (interface{}, error) {
	return body.CreateWithValid(&model.SysDict{}, service.db, nil, func(model interface{}) error {
		//return util.CtxGetValidParams(ctx, model, service, "Unique")
		return nil
	})
}

func (service DictServiceImpl) Update(body gocrud.FormBody) (interface{}, error) {
	return body.Update(&model.SysDict{}, service.db.Select("Name", "Remark"), nil)
}

func (service DictServiceImpl) Edit(body gocrud.EditorBody) error {
	return body.Updates(&model.SysDict{}, service.db, nil)
}

func (service DictServiceImpl) Options(key string, language string) []map[string]interface{} {
	var sysDictItem []*model.SysDictItem
	tx := service.db.Where("sign = ?", key)
	queryReader := reader.NewQueryReader(tx, 1, 1)
	queryReader.ReaderAll(&sysDictItem)
	return formatter.ToDataList(sysDictItem, nil)
}
